package com.fsd.admin.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;
import com.fsd.admin.dao.E_AutoreplyDao;
import com.fsd.admin.entity.E_autoreplyEntity;
import com.fsd.admin.model.A_Employee;
import com.fsd.admin.model.E_Autoreply;
import com.fsd.admin.model.E_Autoreplykey;
import com.fsd.admin.model.E_Autoreplylist;
import com.fsd.admin.model.E_wechat;
import com.fsd.admin.service.E_AutoreplyService;
import com.fsd.admin.service.E_AutoreplykeyService;
import com.fsd.admin.service.E_AutoreplylistService;
import com.fsd.admin.service.Sys_SystemParametersService;
import com.fsd.core.common.BusinessException;
import com.fsd.core.util.Config;
import com.fsd.core.util.EhcacheUtil;
import com.fsd.core.util.ParametersUtil;
import com.google.gson.Gson;

@Service("e_autoreplyServiceImpl")
public class E_AutoreplyServiceImpl extends MainServiceImpl<E_Autoreply, String> implements E_AutoreplyService {
	
	private static final Logger log = Logger.getLogger(E_AutoreplyServiceImpl.class);
	private String depict = "自动回复";
	
	@Resource(name = "e_autoreplyDaoImpl")
	public void setBaseDao(E_AutoreplyDao e_autoreplyDao) {
		super.setBaseDao(e_autoreplyDao);
	}

	@Resource(name = "e_autoreplyDaoImpl")
	private E_AutoreplyDao autoreplyDao;
	
	@Resource(name = "e_autoreplykeyServiceImpl")
	private E_AutoreplykeyService autoreplykeyService;
	
	@Resource(name = "e_autoreplylistServiceImpl")
	private E_AutoreplylistService autoreplylistService;
	
	@Resource(name = "Sys_SystemParametersServiceImpl")
	private Sys_SystemParametersService sysParametersService;
	
	private static final Lock lock = new ReentrantLock();
	
	/**
	 * 收集整理处理消息
	 */
	private Map<String, E_autoreplyEntity> getMessageProcessMap(String wechatid, String key) throws Exception{
		lock.lock();
		Map<String, Map<String, E_autoreplyEntity>> objectMap = null;
		String strKey = Config.E_AUTOREPLYMAP + wechatid;
		try {
			if(EhcacheUtil.getInstance().get(strKey) == null){
				objectMap = new HashMap<String, Map<String,E_autoreplyEntity>>();
				//关键字全匹配
				Map<String, E_autoreplyEntity> keyQPMap = new HashMap<String, E_autoreplyEntity>();
				objectMap.put(Config.WECHATPROCESSQP, keyQPMap);
				//关键字模糊匹配
				Map<String, E_autoreplyEntity> keyMHMap = new HashMap<String, E_autoreplyEntity>();
				objectMap.put(Config.WECHATPROCESSMH, keyMHMap);
				//事件匹配
				Map<String, E_autoreplyEntity> clickMap = new HashMap<String, E_autoreplyEntity>();
				objectMap.put(Config.WECHATPROCESSCD, clickMap);
				//系统匹配
				Map<String, E_autoreplyEntity> systemMap = new HashMap<String, E_autoreplyEntity>();
				objectMap.put(Config.WECHATPROCESSXT, systemMap);
				List<E_Autoreply> replyList = autoreplyDao.queryByHql(
						"from E_Autoreply a where a.wechatid = '"+ wechatid + 
						"' and status = 'e_wxhfqy' order by sort asc");
				List<E_Autoreplykey> keyList = autoreplykeyService.getObjectListByWeChatID(wechatid);
				Map<String, List<E_Autoreplykey>> keyMap = new HashMap<String, List<E_Autoreplykey>>();
				for (E_Autoreplykey autoreplykey : keyList) {
					if (!keyMap.containsKey(autoreplykey.getAutoreplyid())){
						keyMap.put(autoreplykey.getAutoreplyid(), new ArrayList<E_Autoreplykey>());
					}
					keyMap.get(autoreplykey.getAutoreplyid()).add(autoreplykey);
				}
				List<E_Autoreplylist> lstList = autoreplylistService.getObjectListByWeChatID(wechatid);
				Map<String, List<E_Autoreplylist>> lstMap = new HashMap<String, List<E_Autoreplylist>>();
				for (E_Autoreplylist autoreplylist : lstList) {
					if (!lstMap.containsKey(autoreplylist.getAutoreplyid())){
						lstMap.put(autoreplylist.getAutoreplyid(), new ArrayList<E_Autoreplylist>());
					}
					lstMap.get(autoreplylist.getAutoreplyid()).add(autoreplylist);
				}
				E_autoreplyEntity replyEntity = null;
				for (E_Autoreply reply : replyList) {
					replyEntity = new E_autoreplyEntity();
					replyEntity.setId(reply.getId());
					replyEntity.setKeyword(reply.getKeyword());
					replyEntity.setMessagetype(reply.getMessagetype());
					replyEntity.setReplytype(reply.getReplytype());
					replyEntity.setContent(reply.getContent());
					if (reply.getMessagetype().equals(Config.WECHATMESSAGEXT)){
						replyEntity.setKey(reply.getId());
						if (reply.getReplytype().equals(Config.WECHATREPLYLB)){
							replyEntity.setAutoreplylist(lstMap.get(reply.getId()));
						}
						systemMap.put(replyEntity.getKey(), replyEntity);
					}else if (reply.getMessagetype().equals(Config.WECHATMESSAGECD)){
						keyList = keyMap.get(reply.getId());
						for (E_Autoreplykey autoreplykey : keyList) {
							replyEntity.setKey(autoreplykey.getKeyword());
							if (reply.getReplytype().equals(Config.WECHATREPLYLB)){
								replyEntity.setAutoreplylist(lstMap.get(reply.getId()));
							}
							clickMap.put(replyEntity.getKey(), replyEntity);
							break;
						}
					}else if (reply.getMessagetype().equals(Config.WECHATMESSAGEGJ)){
						keyList = keyMap.get(reply.getId());
						for (E_Autoreplykey autoreplykey : keyList) {
							replyEntity = new E_autoreplyEntity();
							replyEntity.setId(reply.getId());
							replyEntity.setMessagetype(reply.getMessagetype());
							replyEntity.setReplytype(reply.getReplytype());
							replyEntity.setContent(reply.getContent());
							replyEntity.setKey(autoreplykey.getKeyword());
							if (replyEntity.getReplytype().equals(Config.WECHATREPLYLB)){
								replyEntity.setAutoreplylist(lstMap.get(reply.getId()));
							}
							if (autoreplykey.getMatched().equals("true")){
								if (!keyQPMap.containsKey(replyEntity.getKey())){
									keyQPMap.put(replyEntity.getKey(), replyEntity);
								}
							}else{
								if (!keyMHMap.containsKey(replyEntity.getKey())){
									keyMHMap.put(replyEntity.getKey(), replyEntity);
								}
							}
						}
					}
				}
				EhcacheUtil.getInstance().put(strKey, objectMap);
			}else{
				objectMap = (Map<String, Map<String, E_autoreplyEntity>>)EhcacheUtil.getInstance().get(strKey);
			}
		} finally {
			lock.unlock();
		}
		if (objectMap != null && objectMap.containsKey(key))
			return objectMap.get(key);
		else
			return null;
	}
	
	/**
	 * 文本消息处理消息
	 * @throws Exception 
	 */
	public E_autoreplyEntity getReplyTextMessage(String wechatid, String message) throws Exception{
		Map<String, E_autoreplyEntity> replyMap = this.getMessageProcessMap(wechatid, Config.WECHATPROCESSQP);
		if (replyMap.containsKey(message)){
			return replyMap.get(message);
		}
		replyMap = this.getMessageProcessMap(wechatid, Config.WECHATPROCESSMH);
		for (String key : replyMap.keySet()) {
			if (message.indexOf(key) != -1){
				return replyMap.get(key);
			}
		}
		return null;
	}
	
	/**
	 * 事件消息处理消息
	 * @throws Exception 
	 */
	public E_autoreplyEntity getReplyClickMessage(String wechatid, String code) throws Exception{
		Map<String, E_autoreplyEntity> replyMap = this.getMessageProcessMap(wechatid, Config.WECHATPROCESSCD);
		if (replyMap.containsKey(code)){
			return replyMap.get(code);
		}
		return null;
	}
	
	/**
	 * 系统消息处理消息
	 * @throws Exception 
	 */
	public E_autoreplyEntity getReplySystemMessage(String wechatid, String code) throws Exception{
		Map<String, E_autoreplyEntity> replyMap = this.getMessageProcessMap(wechatid, Config.WECHATPROCESSXT);
		if (replyMap.containsKey(code)){
			return replyMap.get(code);
		}
		return null;
	}
	
	/**
	 * 保存对象（添加、修改）
	 * @param obj
	 * @param a_employee
	 * @param a_company
	 * @throws Exception
	 */
	public void saveObject(E_Autoreply obj, ParametersUtil param, A_Employee employee) throws Exception{
		if(param.getJsonData() == null || "".equals(param.getJsonData())){
			throw new BusinessException(depict + "未找到自动回复的提交参数，无法保存!");
		}
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
		E_Autoreplykey[] keyArray = gs.fromJson(gs.toJson(objectMap.get("keyobjs")), E_Autoreplykey[].class);
		E_Autoreplylist[] lstArray = gs.fromJson(gs.toJson(objectMap.get("lstobjs")), E_Autoreplylist[].class);
		String keys = "";
		if (!obj.getMessagetype().equals(Config.WECHATMESSAGEXT)){
			if (keyArray.length == 0){
				throw new BusinessException(depict + "自动回复的关键字不得为空，无法保存!");
			}
			for (int i = 0; i < keyArray.length; i++) {
				if (!keys.equals("")){
					keys += "|";
				}
				keys += keyArray[i].getKeyword();
			}
		}
		if (obj.getReplytype().equals(Config.WECHATREPLYLB)){
			if (lstArray.length == 0){
				throw new BusinessException(depict + "回复列表不得为空，无法保存!");
			}
		}
		if(obj.getId() != null && !"".equals(obj.getId())){
			//修改
			E_Autoreply old_obj = autoreplyDao.get(obj.getId());
			old_obj.setName(obj.getName());
			old_obj.setMenuid(obj.getMenuid());
			old_obj.setMenuname(obj.getMenuname());
			old_obj.setKeyword(keys);
			old_obj.setReplytype(obj.getReplytype());
			old_obj.setReplytypename(obj.getReplytypename());
			old_obj.setContent(obj.getContent());
			old_obj.setSort(obj.getSort());
			old_obj.setStatus(obj.getStatus());
			old_obj.setStatusname(obj.getStatusname());
			old_obj.setRemark(obj.getRemark());
			old_obj.setStatus(obj.getStatus());
			old_obj.setStatusname(obj.getStatusname());
			old_obj.setUpdatedate(this.getData());
			old_obj.setUpdateemployeeid(employee.getId());
			old_obj.setUpdateemployeename(employee.getRealname());
			autoreplyDao.update(old_obj);

			autoreplykeyService.delObjectByAutoReplyID("'" + old_obj.getId() + "'");
			autoreplylistService.delObjectByAutoReplyID("'" + old_obj.getId() + "'");
		}else{
			//新增
			if (obj.getMessagetype().equals(Config.WECHATMESSAGEXT)){
				throw new BusinessException(depict + "不准新增系统信息类型回复!");
			}
			obj.setId(this.getUUID());
			obj.setCompanyid(employee.getCompanyid());
			obj.setAdddate(this.getData());
			obj.setAddemployeeid(employee.getId());
			obj.setAddemployeename(employee.getRealname());
			obj.setKeyword(keys);
			autoreplyDao.save(obj);
		}
		if(keyArray.length > 0){
			for (int i = 0; i < keyArray.length; i++) {
				keyArray[i].setId(this.getUUID());
				keyArray[i].setCompanyid(employee.getCompanyid());
				keyArray[i].setWechatid(obj.getWechatid());
				keyArray[i].setAutoreplyid(obj.getId());
				autoreplykeyService.save(keyArray[i]);
			}
		}
		if(lstArray.length > 0){
			for (int i = 0; i < lstArray.length; i++) {
				lstArray[i].setId(this.getUUID());
				lstArray[i].setCompanyid(employee.getCompanyid());
				lstArray[i].setWechatid(obj.getWechatid());
				lstArray[i].setAutoreplyid(obj.getId());
				if (!lstArray[i].getImageurl().trim().equals("") && 
						lstArray[i].getImageurl().toLowerCase().indexOf("http") == -1){
					String url = sysParametersService.getParameterValueByCode(Config.SITEMANAGEURL, employee.getCompanyid());
					lstArray[i].setImageurl(url + lstArray[i].getImageurl());
				}
				autoreplylistService.save(lstArray[i]);
			}
		}
		EhcacheUtil.getInstance().remove(Config.E_AUTOREPLYMAP + obj.getWechatid());
		this.sysLogService.saveObject(Config.LOGTYPEBC, this.depict + obj.getId() + obj.getName(), employee, E_AutoreplyServiceImpl.class);
		log.info(this.depict + "保存成功");
	}
	
	/**
	 * 彻底删除对象
	 * @param parameters
	 */
	@SuppressWarnings("unchecked")
	public void delObject(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		String ids = "";
		String idObj = "";
		for (String id : dir) {
			if (!ids.equals("")){
				ids += ",";
			}
			ids += "'" + id + "'";
			idObj = id;
		}
		E_Autoreply reply = autoreplyDao.get(idObj);
		autoreplyDao.executeHql("delete from E_Autoreply where id in (" + ids + ")");
		autoreplykeyService.delObjectByAutoReplyID(ids);
		autoreplylistService.delObjectByAutoReplyID(ids);
		EhcacheUtil.getInstance().remove(Config.E_AUTOREPLYMAP + reply.getWechatid());
	}

	/**
	 * 加载分页数据
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getObjectPageList(ParametersUtil param, A_Employee employee) throws Exception{
		if(param.getJsonData() == null || "".equals(param.getJsonData())){
			throw new BusinessException(depict + "未找到自动回复的相关参数!");
		}
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(param.getJsonData(), Map.class);
		Criteria c = autoreplyDao.createCriteria();
		c.add(Restrictions.eq("companyid", employee.getCompanyid()));
		c.add(Restrictions.eq("wechatid", objectMap.get("wxid")));
		c.addOrder(Order.asc("sort"));
		if(objectMap.get("name") != null && !"".equals(objectMap.get("name"))){
			c.add(Restrictions.like("name", "%" + objectMap.get("name") + "%"));
		}
		return autoreplyDao.findPager(param , c);
	}
	
	/**
	 * 根据ID加载对象
	 * @param parameters
	 * @return
	 * @throws Exception
	 */
	public ParametersUtil getObjectById(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		if(objectMap.get("id") == null && "".equals(objectMap.get("id"))){
			throw new BusinessException(depict + "获取缺少ID参数!");
		}
		E_Autoreply obj = autoreplyDao.get(objectMap.get("id").toString());
		if(obj == null){
			throw new BusinessException(depict + "数据不存在!");
		}
		ParametersUtil util = new ParametersUtil();
		util.addSendObject("data", obj);
		util.addSendObject("keyobjs", autoreplykeyService.getObjectListByAutoReplyID(obj.getId()));
		util.addSendObject("lstobjs", autoreplylistService.getObjectListByAutoReplyID(obj.getId()));
		return util;
	}
	
	/**
	 * 修改对象状态
	 * @param parameters
	 */
	@SuppressWarnings("unchecked")
	public void updateEnabledObject(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		ArrayList<String> dir = (ArrayList<String>) objectMap.get("ids");
		boolean isEnabled = (Boolean) objectMap.get("isenabled");
		String ids = "";
		String idObj = "";
		for (String id : dir) {
			if (!ids.equals("")){
				ids += ",";
			}
			ids += "'" + id + "'";
			idObj = id;
		}
		if (isEnabled)
			autoreplyDao.executeHql("update E_Autoreply t set t.status = 'e_wxhfqy', t.statusname = '启用' where t.id in (" + ids + ")");
		else
			autoreplyDao.executeHql("update E_Autoreply t set t.status = 'e_wxhfty', t.statusname = '停用' where t.id in (" + ids + ")");
		E_Autoreply reply = autoreplyDao.get(idObj);
		EhcacheUtil.getInstance().remove(Config.E_AUTOREPLYMAP + reply.getWechatid());
	}
	
	/**
	 * 顺序排序
	 * @param parameters
	 */
	public void updateSortObject(ParametersUtil parameters) throws Exception{
		Gson gs = new Gson();
		Map objectMap = gs.fromJson(parameters.getJsonData(), Map.class);
		List<String> idList = (List<String>) objectMap.get("ids");
		String ids = this.getSQLinByIDList(idList);
		E_Autoreply objDW = autoreplyDao.get(objectMap.get("id").toString());
		if (objDW == null)
			throw new BusinessException(depict + "获取定位对象为空!");
		List<E_Autoreply> objList = autoreplyDao.queryByHql("from E_Autoreply t where " +
				"t.wechatid = '" + objDW.getWechatid() + "' " +
				"and t.id not in (" + ids + ") " +
				"and t.sort >= " + objDW.getSort() + " order by t.sort asc");
		long sort = objDW.getSort();
		for (String id : idList) {
			autoreplyDao.executeHql("update E_Autoreply t set t.sort = " + sort + " where t.id = '" + id + "'");
			sort++;
		}
		for (E_Autoreply obj : objList) {
			autoreplyDao.executeHql("update E_Autoreply t set t.sort = " + sort + " where t.id = '" + obj.getId() + "'");
			sort++;
		}
		EhcacheUtil.getInstance().remove(Config.E_AUTOREPLYMAP + objDW.getWechatid());
	}
	
	/**
	 * 微信账号初始化，添加自动回复系统值
	 * @param wechat
	 */
	public void saveInitSystemAutoReply(E_wechat wechat) throws Exception{
		E_Autoreply obj = new E_Autoreply();
		obj.setId("WECHATMEGSUBSCRIBE");
		obj.setCompanyid(wechat.getCompanyid());
		obj.setWechatid(wechat.getId());
		obj.setName("被关注自动回复");
		obj.setMessagetype(Config.WECHATMESSAGEXT);
		obj.setMessagetypename("系统消息");
		obj.setReplytype(Config.WECHATREPLYNR);
		obj.setReplytypename("内容回复");
		obj.setContent("感谢您的关注！");
		obj.setSort(1L);
		obj.setStatus("e_wxhfqy");
		obj.setStatusname("启用");
		obj.setRemark("账号被关注时自动回复内容");
		obj.setAdddate(this.getData());
		obj.setAddemployeeid(wechat.getAddemployeeid());
		obj.setAddemployeename(wechat.getAddemployeename());
		autoreplyDao.save(obj);
		
		obj = new E_Autoreply();
		obj.setId("WECHATMEGDEFAULT");
		obj.setCompanyid(wechat.getCompanyid());
		obj.setWechatid(wechat.getId());
		obj.setName("默认自动回复");
		obj.setMessagetype(Config.WECHATMESSAGEXT);
		obj.setMessagetypename("系统消息");
		obj.setReplytype(Config.WECHATREPLYNR);
		obj.setReplytypename("内容回复");
		obj.setContent("感谢您的到来！");
		obj.setSort(2L);
		obj.setStatus("e_wxhfqy");
		obj.setStatusname("启用");
		obj.setRemark("未找到对应回复语，默认统一回复内容");
		obj.setAdddate(this.getData());
		obj.setAddemployeeid(wechat.getAddemployeeid());
		obj.setAddemployeename(wechat.getAddemployeename());
		autoreplyDao.save(obj);
	}
	
}
